import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import autobind from "autobind-decorator";
import { setTitle } from "../../../utils/dingtalk.js";
import { Button } from "@ali/ding-ui";
import Icon from "../../../components/Icon/index.jsx";
import lwp from "../../../utils/lwp";
import { get } from "../../../utils/db";
import HelpModal from "../../../components/HelpModal";


const mapStateToProps = state => ({});
const mapDispatchToProps = dispatch => ({
    actions: bindActionCreators(
        {
            dispatch
        },
        dispatch
    )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class Initialize extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedNum: 0,
            seletedUserIds: [],
            alreadyAdminIds: []
        };
        setTitle({
            title: "一步开启智能人事"
        });
        
        window._rlog(`_hrcenter_initialize`);
    }

    componentDidMount() {
        const getAdminUri = "/r/Adaptor/HRMCommonI/getSuperAdminWithBosses";
        const data = [
            get('corpId')
        ]
        lwp(getAdminUri, { body: data }).then( res =>{
            console.log(getAdminUri)
            console.log(res);
            const responseText = JSON.parse(res.responseText);
            if (res.statusCode === 200 && responseText) {
                console.log(responseText)
                const superAdminList = [responseText.superAdminUserId];
                const bossesUserIdList = responseText.bossesUserIdList;
                const adminList = Array.from(new Set(superAdminList.concat(bossesUserIdList)));
                this.setState({
                    alreadyAdminIds: adminList,
                    selectedNum: adminList.length
                })
            }
        }).catch(err => {
            console.log(err);
        });
    }

    @autobind
    pickAdmin() {
        dd.biz.contact.complexPicker({
            title: "选择管理员",
            corpId: get('corpId'),
            multiple: true,
            pickedUsers: this.state.seletedUserIds,
            requiredUsers: this.state.alreadyAdminIds,
            responseUserOnly:true,
            onSuccess: (res) => {
                console.log(res)
                const seleted_user_ids = []
                if(res.selectedCount > 0) {
                    for (const user of res.users) {
                        if (this.state.alreadyAdminIds.indexOf(user.emplId) < 0) {
                            seleted_user_ids.push(user.emplId)
                        }
                    }
                    console.log(seleted_user_ids);
                    this.setState({
                        seletedUserIds: seleted_user_ids,
                        selectedNum: res.selectedCount
                    })
                }
            },
            onFail : function(err) {
                console.log(err);
            }
        });
    }

    @autobind
    setupAdmin() {
        window._rlog(`_hrcenter_initialize_set`);
        const initHrmUri = "/r/Adaptor/HRMCommonI/initHrm";
        const data = [
            get('corpId'),
            this.state.seletedUserIds
        ];
        console.log(data);
        lwp(initHrmUri, { body: data }).then( res =>{
            console.log(res);
            if (res.statusCode === 200) {
                window.__auth = "";
                window.location.replace("#/hrcenter/manage");
                //window.location.reload();
            } else {
                alert('授权失败！')
            }
        }).catch(err => {
            console.log(err);
        });
    }

    render() {
        return (
            <div className="initialize-container growth-container">
                <div className="scroll-body">
                    <div className="grey_space"></div>
                    <div className="admin_picker" onClick={this.pickAdmin}>
                        设置人事管理员
                        <span className="admin_num">
                            {this.state.selectedNum}人
                            <Icon type="right" />
                        </span>
                    </div>
                    <p className="hint">当前主管理员和企业负责人已默认开通智能人事管理权限</p>                    
                    <div className="feature_img">
                        <img src="https://gw.alicdn.com/tfs/TB1Jt6WXiqAXuNjy1XdXXaYcVXa-1125-1235.png" alt=""/>
                    </div>
                </div>
                <div className="scroll-btn scroll-btn-preview">
                    <Button
                        className="preview-button"
                        type="primary"
                        onClick={this.setupAdmin}
                    >
                    设置完成
                </Button>
                </div>
                <HelpModal/>
            </div>
        );
    }
}
